<template>
  <div>
    <el-form inline>
      <el-form-item :label="queryTime.label">
        <el-date-picker :type="queryTime.type" v-model="queryParams.time" :value-format="queryTime.format"
          @change="handleDate" />
      </el-form-item>
      <el-form-item>{{ $t('analysis.DayAndStorageTips',[totalDay,  totalChildrenCount]) }}</el-form-item>
      <el-form-item :label="$t('analysis.Sort')">
        <el-switch v-model="sourceAsc" :active-text="$t('analysis.Desc')" :inactive-text="$t('analysis.Asc')"
          @change="updateChart" />
      </el-form-item>
    </el-form>
    <div ref="chart" style="width: 90vw;height: 45vh;"></div>
    <!-- <div>{{ result }}</div> -->
  </div>
</template>
<script>
  import deviceAPI from '@/api/device/device'
  import deviceAnalysisAPI from '@/api/device/analysis'
  import * as echarts from 'echarts'
  import {
    DeviceType
  } from '@/views/device/common'
  import ListAnalysis from '@/utils/ListAnalysis'
  import {
    getLastMonthString,
    getMonthDayCount
  } from './utils'
  export default {
    name: 'MaxBarByMonth',
    data() {
      return {
        chartOption: {
          title: {
            text: this.$t('analysis.MaxPercentByMonth'),
            left: 'center'
          },
          tooltip: {
            show: true
          },
          xAxis: [{
            type: 'category'
          }],
          yAxis: [{
            type: 'value',
            show: true
          }],
          series: [{
            name: this.$t('analysis.MaxPercent'),
            type: 'bar'
          }]
        },
        queryTime: {
          label: this.$t('analysis.Month'),
          type: 'month',
          valueFormat: 'yyyy-MM'
        },
        queryParams: {
          time: null,
          startDate: null,
          endDate: null,
          deviceId: null,
        },
        lockerList: [],
        children: [],
        chart: null,
        totalDay: 0,
        totalChildrenCount: 0,
        sourceAsc: false,
        result: {
          map: {},
          list: []
        },
      }
    },
    created() {
      this.setQueryTime()
      this.loadLocker()
      this.queryPermission()
    },
    mounted() {
      setTimeout(this.createChart, 300)
    },
    methods: {
      loadLocker() {
        const vm = this
        deviceAPI.list({
          type: DeviceType.LOCKER
        }).then(res => {
          vm.lockerList = [].concat(res.data)
          const list = res.data
          var count = 0
          for (var i = 0; i < list.length; i++) {
            count += list[i].childrenSize
          }
          this.totalChildrenCount = count
        })
      },
      queryPermission() {
        const vm = this
        deviceAnalysisAPI.childrenFrequency(this.queryParams).then(res => {
          vm.children = [].concat(res.data)
          vm.doAnalysis()
        })
      },
      createChart() {
        const el = this.$refs['chart']
        this.chart = echarts.init(el);
        this.chart.setOption(this.chartOption)
        this.updateChart();
      },
      setQueryTime() {
        this.queryParams.time = getLastMonthString()
        this.totalDay = getMonthDayCount(this.queryParams.time)
      },
      handleDate() {
        this.totalDay = getMonthDayCount(this.queryParams.time)
        this.queryPermission()
      },
      doAnalysis() {
        const list = this.children
        if (list === null || list.length === 0) {
          this.result.list = []
        } else {
          const analysis = new ListAnalysis(this.children)
          this.result = analysis.groupBy(['deviceName'], ['deviceIndex'])
        }
        this.updateChart()
      },
      updateChart() {
        if (this.chart === null) {
          return
        }
        const source = this.lockerList
        const {
          map
        } = this.result
        for (var i = 0; i < source.length; i++) {
          const each = source[i]
          const stat = map['deviceName:' + each.name]
          each.maxUse = stat === undefined ? 0 : (stat['deviceIndex-count'] / each.childrenSize * 100)
        }

        const vm = this
        const updateOption = {
          yAxis: [{
            name: '%'
          }],
          dataset: [{
            dimensions: ['name', 'maxUse'],
            source: source.sort(function (a, b) {
              return vm.sourceAsc ? a.maxUse - b.maxUse : b.maxUse - a.maxUse
            })
          }]
        }
        this.chart.setOption(updateOption);
      }
    }
  }

</script>
